package com.zhny.sensor.controller;

import com.zhny.sensor.entity.Message;
import com.zhny.sensor.service.BarcodeMachineService;
import com.zhny.sensor.utils.OrderType;
import com.zhny.sensor.utils.RedisUtil;
import com.zhny.sensor.utils.Result;
import com.zhny.sensor.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@RestController
@CrossOrigin
@RequestMapping("/monitor")
public class MonitorController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BarcodeMachineService barcodeMachineService;

    /**
     * 这里有个问题就是如果仅仅把设备id当作键去存可能会出现重复的情况，后期键值可以改成 屠宰场id+设备id
     * 通过设备id查询出指令
     * 如果redis超过40条则去除20条。
     * @return
     */
    @RequestMapping(value = "/{number}", method = RequestMethod.GET)
    public Result queryRecord(@PathVariable String number) {
        //封装结果集
        List<Message> res;
        //查看该脚标机的指令条数
        long size = redisUtil.lGetListSize(number);
        System.out.println("当前存在的指令条数为"+size);
        if (size > 40) {
            //如果条数大于40条，则去掉前20条数据
            redisUtil.lTrim(number, 20, size);
            size = redisUtil.lGetListSize(number);
        }
        //只发送不超过20条的数据给前端
        if (size > 20) {
            res = (List) redisUtil.lGet(number, size - 20, size);
        } else {
            res = (List) redisUtil.lGet(number, 0, -1);
        }
        //将指令数换成具体指令
        for (Message m : res) {
            int index = Integer.valueOf(m.getOrder());
            m.setOrder(OrderType.types[index]);
        }
        return new Result(true, StatusCode.OK, "查询成功", res);
    }

    /**
     * 根据屠宰场id查询脚标机设备id
     */
    @RequestMapping(value = "/queryBarcodeMachine/{slaughterHouseId}", method = RequestMethod.GET)
    public Result queryBarcodeMachines(@PathVariable String slaughterHouseId) {
        return new Result(true, StatusCode.OK, "查询设备成功", barcodeMachineService.queryBarcodeMachine(slaughterHouseId));
    }

}
